#include <iostream>
#include <queue>
#include <pthread.h>

template<class T>
class BlockQueue
{
public:
    BlockQueue(int capacity)
        : _capacity(capacity)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_pCond, nullptr);
        pthread_cond_init(&_cCond, nullptr);
    }

    ~BlockQueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_pCond);
        pthread_cond_destroy(&_cCond);
    }

    bool IsFull()
    {
        return _blockqueue.size() == _capacity;
    }

    bool IsEmpty()
    {
        return _blockqueue.size() == 0;
    }

    void Push(const T& date)
    {
        pthread_mutex_lock(&_mutex);
        if (IsFull())
        {
            pthread_cond_wait(&_pCond, &_mutex);
        }

        _blockqueue.push(date);
        pthread_cond_signal(&_cCond);
        pthread_mutex_unlock(&_mutex);
    }

    void Pop(T* date)
    {
        pthread_mutex_lock(&_mutex);
        if (IsEmpty())
        {
            pthread_cond_wait(&_cCond, &_mutex);
        }

        *date = _blockqueue.front();
        _blockqueue.pop();
        pthread_cond_signal(&_pCond);
        pthread_mutex_unlock(&_mutex);
    }

private:
    std::queue<T> _blockqueue;
    size_t _capacity;
    pthread_mutex_t _mutex;

    pthread_cond_t _pCond;  //生产者
    pthread_cond_t _cCond;  //消费者
};